<template>
  <div class="app-container">
    <!-- 用户导入对话框 -->
    <el-dialog
      title="导入"
      v-model="open"
      width="400px"
      append-to-body
    >
      <el-upload
       :key="keys"
        ref="upload"
        :limit="2"
        accept=".xlsx, .xls"
        :headers="headers"
        :action="uploadFileUrl"
        :file-list="fileList"
        @change="chaFun"
        :before-upload="handleBeforeUpload"
        :on-success="handleUploadSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!-- <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div> -->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
           v-if="down"
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click.stop="downFun"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
  import {
  reactive,
  toRefs
} from 'vue'
import { getToken } from "@/utils/auth";
const data = reactive({
  modelVisible: false,
  historyVisible: false, 
  reportVisible: false, 
})

const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 5,
  },
  down: {
    type: String,
    default: '',
  },
  url: {
    type: String,
    default: '',
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 500,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["doc", "xls", "xls", "xlsx", "ppt", "txt", "pdf", 'mpeg', 'm4v', 'mov', 'asf', 'rmvb', 'rm', 'jpg', 'png'],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  }
});


const open = ref(false)
const { proxy } = getCurrentInstance();
const emit = defineEmits();
const number = ref(0);
const uploadList = ref([]);
const baseUrl = '';
const metaUrl = ref(import.meta.env.VITE_APP_BASE_API)
const uploadFileUrl = ref(''); // 上传的图片服务器地址
uploadFileUrl.value = metaUrl.value + props.url
const keys = ref(0)
// console.log('props.url',uploadFileUrl.value)
watch(() => props.url, val => {
  keys.value = new Date().getTime();
  uploadFileUrl.value = metaUrl.value + props.url
});
const headers = ref({ token: getToken() });
const fileList = ref([]);
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);
const downFun = () => {
  var a = document.createElement('a')
  a.href = props.down
  a.download = new Date().getTime() + '.xlsx'
  a.click()
}
watch(() => props.modelValue, val => {
  if (val) {
    let temp = 1;
    // 首先将值转为数组
    const list = Array.isArray(val) ? val : props.modelValue.split(',');
    // 然后将数组转为对象数组
    fileList.value = list.map(item => {
      if (typeof item === "string") {
        item = { name: item, url: item };
      }
      item.uid = item.uid || new Date().getTime() + temp++;
      return item;
    });
  } else {
    fileList.value = [];
    return [];
  }
},{ deep: true, immediate: true });
const chaFun = (file) => {
  
  if (fileList.value.length >= 2) {
    fileList.value = [file]
  }
  console.log('file3124', file)
  console.log('232', fileList.value)
}
// 上传前校检格式和大小
function handleBeforeUpload(file) {
  console.log('file', file)
  // 校检文件类型
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    const isTypeOk = props.fileType.some((type) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  proxy.$modal.loading("正在上传文件，请稍候...");
  number.value++;
  return true;
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.msgError("上传文件失败");
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  emit("succFun", res);
  proxy.$modal.closeLoading();
  // uploadList.value.push({ name:  res.data.name, url: res.data.url });
  // if (uploadList.value.length === number.value) {
  //   fileList.value = fileList.value.filter(f => f.url !== undefined).concat(uploadList.value);
  //   uploadList.value = [];
  //   number.value = 0;
  //   emit("update:modelValue", listToString(fileList.value));
  //   proxy.$modal.closeLoading();
  // }
}

// 删除文件
function handleDelete(index) {
  fileList.value.splice(index, 1);
  emit("update:modelValue", listToString(fileList.value));
}

// 获取文件名称
function getFileName(name) {
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return "";
  }
}

// 对象转成指定字符串分隔
function listToString(list, separator) {
  let strs = "";
  separator = separator || ",";
  for (let i in list) {
    if(undefined !== list[i].url) {
      strs += list[i].url + separator;
    }
  }
  return strs != '' ? strs.substr(0, strs.length - 1) : '';
}
const submitFileForm = () => {
  proxy.$refs.upload.submit();
  open.value = false
}
const openTure = () => {
  fileList.value = []
  open.value = true
}
defineExpose({

  openTure

})
</script>